import * as dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import * as timezone from 'dayjs/plugin/timezone';
import * as utc from 'dayjs/plugin/utc';
import type { Dayjs } from 'dayjs';

(dayjs as any).extend(utc);
(dayjs as any).extend(timezone);
(dayjs as any).locale('zh-cn');

export const today = dayjs().format('YYYY-MM-DD')

export const previousDay = () => {
  const weekDateList = getCurrentWeekDates()
  if (weekDateList.includes(today)) {
    if (today === weekDateList[0]) {
      return today
    } else {
      return addDate(today, -1, 'day');
    }
  } else {
    return weekDateList[weekDateList.length - 1]
  }
};

export const addDate = (
  date: number | string | Date | Dayjs,
  num: number,
  type: dayjs.ManipulateType
) => dayjs(date).add(num, type);

export const getStartOrEndDate = (dateType: dayjs.OpUnitType, date = dayjs()) => ({
  start: dayjs(date).startOf(dateType),
  end: dayjs(date).endOf(dateType)
});

const getCurrentWeekDates = (): string[] => {
  const { start } = getStartOrEndDate('week'); // 获取当前周的第一天（周一）
  const dates = [];
  for (let i = 0; i < 5; i++) {
    dates.push(dayjs(start).add(i, 'day').format('YYYY-MM-DD')); // 按天递增
  }
  return dates;
};

/** 格式化时间 YYYY-MM-DD HH:mm:ss */
export const formatTime = (
  time: Date | Dayjs = dayjs(),
  formatString = 'YYYY-MM-DD HH:mm:ss',
) => {
  return dayjs(time).tz('Asia/Shanghai').format(formatString);
};

/** 对比时间是否相同 */
export const compareTime = (date1: string | Dayjs, date2: string | Dayjs) => {
  return dayjs(date1).isSame(dayjs(date2))
}



